package com.cloudz.iptv;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.ViewTarget;
import com.cloudz.iptv.activity.BaseActivity;
import com.cloudz.iptv.api.ApiConstants;
import com.cloudz.iptv.bing.BingActivity;
import com.cloudz.iptv.fragment.BaseFragment;
import com.cloudz.iptv.fragment.footer.FooterFragment;
import com.cloudz.iptv.fragment.header.HeaderFragment;
import com.cloudz.iptv.http.UpdateAppHttpUtil;
import com.cloudz.iptv.utils.APKVersionCodeUtils;
import com.cloudz.iptv.utils.SimplePreference;
import com.cloudz.iptv.utils.xupdate.HProgressDialogUtils;
import com.vector.update_app.UpdateAppBean;
import com.vector.update_app.UpdateAppManager;
import com.vector.update_app.UpdateCallback;
import com.vector.update_app.service.DownloadService;

import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;

import butterknife.BindView;
import cn.jpush.android.api.JPushInterface;

public class MainActivity extends BaseActivity implements BaseFragment.FocusBorderHelper
{

    private String SET_KEY_DEF = "1612914";

    private String SET_KEY = "";

    long firstTime = 0;

    private static final String TAG = "AliSpeechDemo";


    @BindView(R.id.main_bg)
    public RelativeLayout main_bg;

    @Override
    public int getLayoutId()
    {
        return R.layout.activity_main;
    }


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
//        Resources resources = this.getResources();
//        Drawable btnDrawable = resources.getDrawable(R.drawable.bg7);
//        this.getWindow().setBackgroundDrawable(btnDrawable);
//        this.getWindow().setb

//        new DownloadImageTask(main_bg).execute("https://10wallpaper.com/wallpaper/1366x768/1612/Abstract_Gaussian_Blur_Gradient-2016_Vector_Design_HD_Wallpaper_1366x768.jpg");

        int resourceId = R.drawable.bg7;

        Glide.with(this).load(resourceId).into(new ViewTarget<View, GlideDrawable>(main_bg) {
            @Override
            public void onResourceReady(GlideDrawable glideDrawable, GlideAnimation<? super GlideDrawable> glideAnimation)
            {
                this.view.setBackground(glideDrawable.getCurrent());
            }
        });
        //隐藏bar
        if (getSupportActionBar() != null)
        {
            getSupportActionBar().hide();
        }

        FragmentManager manager = getSupportFragmentManager();

        FragmentTransaction transaction = manager.beginTransaction();

        HeaderFragment headerFragment = new HeaderFragment();

        Fragment footerFragment = Fragment.instantiate(this, FooterFragment.class.getName());

        transaction.add(R.id.header, headerFragment);

        transaction.add(R.id.footer, footerFragment);

        transaction.commit();

        validateUpdate();

        // 设置推送
        setPush();
    }


    /**
     * 判断当前手机是否有ROOT权限
     *
     * @return
     */
    public boolean isRoot()
    {
        boolean bool = false;

        try
        {
            if ((!new File("/system/bin/su").exists()) && (!new File("/system/xbin/su").exists()))
            {
                bool = false;
            } else
            {
                bool = true;
            }
            Log.d(TAG, "bool = " + bool);
        } catch (Exception e)
        {

        }
        return bool;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event)
    {
        Log.d(TAG, "<--------info------>" + keyCode);

        long secondTime = System.currentTimeMillis();
        if (secondTime - firstTime > 2000)
        {
            SET_KEY = keyCode + "";
            firstTime = System.currentTimeMillis();
        } else
        {
            SET_KEY += keyCode;
        }

        Log.d(TAG, "<--------SET_KEY------>" + SET_KEY);

        if (SET_KEY_DEF.equals(SET_KEY))
        {
            SET_KEY = "";
            Intent intent = new Intent(MainActivity.this, BingActivity.class);
            startActivity(intent);
            return false;
        }

        switch (keyCode)
        {
            case KeyEvent.KEYCODE_ENTER:     //确定键enter
            case KeyEvent.KEYCODE_DPAD_CENTER:
                Log.d(TAG, "enter--->");

                break;

            case KeyEvent.KEYCODE_BACK:    //返回键
                Log.d(TAG, "back--->");

                return true;   //这里由于break会退出，所以我们自己要处理掉 不返回上一层

            case KeyEvent.KEYCODE_SETTINGS: //设置键
                Log.d(TAG, "setting--->");

                break;

            case KeyEvent.KEYCODE_DPAD_DOWN:   //向下键

                /*    实际开发中有时候会触发两次，所以要判断一下按下时触发 ，松开按键时不触发
                 *    exp:KeyEvent.ACTION_UP
                 */
                if (event.getAction() == KeyEvent.ACTION_DOWN)
                {

                    Log.d(TAG, "down--->");
                }

                break;

            case KeyEvent.KEYCODE_DPAD_UP:   //向上键
                Log.d(TAG, "up--->");

                break;

            case KeyEvent.KEYCODE_0:   //数字键0
                Log.d(TAG, "0--->");

                break;

            case KeyEvent.KEYCODE_DPAD_LEFT: //向左键

                Log.d(TAG, "left--->");

                break;

            case KeyEvent.KEYCODE_DPAD_RIGHT:  //向右键
                Log.d(TAG, "right--->");
                break;

            case KeyEvent.KEYCODE_INFO:    //info键
                Log.d(TAG, "info--->");

                break;

            case KeyEvent.KEYCODE_PAGE_DOWN:     //向上翻页键
            case KeyEvent.KEYCODE_MEDIA_NEXT:
                Log.d(TAG, "page down--->");

                break;


            case KeyEvent.KEYCODE_PAGE_UP:     //向下翻页键
            case KeyEvent.KEYCODE_MEDIA_PREVIOUS:
                Log.d(TAG, "page up--->");

                break;

            case KeyEvent.KEYCODE_VOLUME_UP:   //调大声音键
                Log.d(TAG, "voice up--->");

                break;

            case KeyEvent.KEYCODE_VOLUME_DOWN: //降低声音键
                Log.d(TAG, "voice down--->");

                break;
            case KeyEvent.KEYCODE_VOLUME_MUTE: //禁用声音
                Log.d(TAG, "voice mute--->");
                break;
            default:
                break;
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 验证更新
     */
    public void validateUpdate()
    {

        String baseUrl = SimplePreference.getServerUrl(this);

        Map<String, String> params = new HashMap<>(1);
        params.put("deviceId", SimplePreference.getDeviceId(this));
        params.put("token", ApiConstants.IPTV_TOKEN);
        params.put("appVersion", APKVersionCodeUtils.getVerName(this));
        //最简方式
        new UpdateAppManager
                .Builder()
                //当前Activity
                .setActivity(this)
                //更新地址
                .setUpdateUrl(baseUrl)
                //添加自定义参数，默认version=1.0.0（app的versionName）；apkKey=唯一表示（在AndroidManifest.xml配置）
                .setParams(params)
                //实现httpManager接口的对象
                .setHttpManager(new UpdateAppHttpUtil())
                .build()
                //检测是否有新版本
                .checkNewApp(new UpdateCallback()
                {
                    /**
                     * 有新版本
                     * @param updateApp 新版本信息
                     * @param updateAppManager app更新管理器
                     */
                    @Override
                    protected void hasNewApp(UpdateAppBean updateApp, UpdateAppManager updateAppManager)
                    {
                        //自定义对话框
                        showDiyDialog(updateApp, updateAppManager);
                    }
                });
    }


    /**
     * 自定义对话框
     *
     * @param updateApp
     * @param updateAppManager
     */
    private void showDiyDialog(final UpdateAppBean updateApp, final UpdateAppManager updateAppManager)
    {
        String targetSize = updateApp.getTargetSize();
        String updateLog = updateApp.getUpdateLog();

        String msg = "";

        if (!TextUtils.isEmpty(targetSize))
        {
            msg = "新版本大小：" + targetSize + "\n\n";
        }

        if (!TextUtils.isEmpty(updateLog))
        {
            msg += updateLog;
        }

        AlertDialog.Builder builder = new AlertDialog.Builder(this)
                .setTitle(String.format("是否升级到%s版本？", updateApp.getNewVersion()))
                .setMessage(msg)
                .setPositiveButton("升级", new DialogInterface.OnClickListener()
                {
                    @Override
                    public void onClick(DialogInterface dialog, int which)
                    {
                        updateAppManager.download(new DownloadService.DownloadCallback()
                        {
                            @Override
                            public void onStart()
                            {

                                HProgressDialogUtils.showHorizontalProgressDialog(MainActivity.this, "下载进度", false);
                            }

                            /**
                             * 进度
                             *
                             * @param progress  进度 0.00 -1.00 ，总大小
                             * @param totalSize 总大小 单位B
                             */
                            @Override
                            public void onProgress(float progress, long totalSize)
                            {


                                HProgressDialogUtils.setProgress(Math.round(progress * 100));

                            }

                            /**
                             *
                             * @param total 总大小 单位B
                             */
                            @Override
                            public void setMax(long total)
                            {

                            }

                            /**
                             * 下载完了
                             * @param file 下载的app
                             * @return true ：下载完自动跳到安装界面，false：则不进行安装
                             */
                            @Override
                            public boolean onFinish(File file)
                            {
                                HProgressDialogUtils.cancel();
                                return true;
                            }

                            @Override
                            public void onError(String msg)
                            {
                                Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
                                HProgressDialogUtils.cancel();

                            }

                            @Override
                            public boolean onInstallAppAndAppOnForeground(File file)
                            {
//                                AppUpdateUtils.installApp(MainActivity.this, file);
//                                dialog.dismiss();
                                return false;
                            }
                        });

                        dialog.dismiss();
                    }
                }).setNegativeButton("暂不升级", (dialog, which) -> dialog.dismiss());

        builder.setCancelable(false);
        builder.create().show();
//
    }


    public void setPush()
    {

        // 设置标签，相当于一个组，一个酒店，这里使用酒店id
        Set<String> tags = new TreeSet<>();

        String deviceId = SimplePreference.getDeviceId(this);

        tags.add(deviceId);


        // 返回有效tags
        Set<String> validTags = JPushInterface.filterValidTags(tags);

        // 设置标签
        JPushInterface.setTags(this, 1, validTags);

        // 设置别名
        JPushInterface.setAlias(this, 2, deviceId);
    }

}
